package com.pdstudio.charts;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.pdstudio.app.Application;
import com.pdstudio.bean.WaterStationSingle;
import com.pdstudio.charts.HydrologicalStationView.Mstyle;
import com.pdstudio.http.StationHttpMethod;
import com.pdstudio.util.SharePreferenceUtil;
import com.pdstudio.weather.R;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TextView;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import com.pdstudio.graphview.GraphView;
import com.pdstudio.graphview.GraphView.GraphViewData;
import com.pdstudio.graphview.GraphViewSeries.GraphViewSeriesStyle;
import com.pdstudio.graphview.GraphViewSeries;
import com.pdstudio.graphview.LineGraphView;

public class HydrologicalStationActivity extends Activity {

	// Spinner river, stations;
	private View customLiveIndexTitleView;
	private TextView txtTitle;
	private ImageView backImgBtn;
	
	TabHost tabHost;// 底部tab控件
	
	private String stationId;//站点id
	private String stationName;//站点名称
	private Handler handler=null;
	private SharePreferenceUtil mSpUtil;
	private Application mApplication;


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.hydro_station_main1);
		
		mApplication = Application.getInstance();
		mSpUtil = mApplication.getSharePreferenceUtil();

		
		LinearLayout layout = (LinearLayout) findViewById(R.id.activity_water_detail);
		int resId = mApplication.getApplicationBackground(mSpUtil
				.getWeatherStatus());
		layout.setBackground(getResources().getDrawable(resId));
		
		
		customLiveIndexTitleView = findViewById(R.id.title_water_detail);
		txtTitle = (TextView) customLiveIndexTitleView
				.findViewById(R.id.title2_text_nav);
		txtTitle.setText("水位曲线图");
		
		try{
			Bundle bundle = this.getIntent().getExtras();
			if(bundle!=null){
				stationId=bundle.getString("staioninfo");	
			}
			
			handler=new Handler(){
					public void handleMessage(Message msg) {
						if (msg.what == 0) {
							if(msg.obj!=null){
								WaterStationSingle wss=(WaterStationSingle)msg.obj;
								initialInfo2(wss);
							}
						}}
			};
		}catch(Exception e){e.printStackTrace();}
		
		backImgBtn = (ImageView)findViewById(R.id.title2_back);
		backImgBtn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub				
				HydrologicalStationActivity.this.finish();
			}
			
		});
		
		initial();
		

	}

	private void initial() {

		initalSpinner();
		
		try{
			Thread thread=new Thread(){
				@Override
				public void run(){
					StationHttpMethod shm=new StationHttpMethod(getApplicationContext());
					WaterStationSingle wss=shm.GetStationSingle(Application.getInstance().getSharePreferenceUtil().getAuthCode(), stationId);
					Message m=new Message();
					m.what=0;
					m.obj=wss;
					handler.sendMessage(m);
				}
			};
			thread.start();
		}catch(Exception e){e.printStackTrace();}
		
		//TextView station = (TextView) findViewById(R.id.tv_hydro_stationname);
		// station.setText("成绩令");
		// TextView position = (TextView) findViewById(R.id.tv_hydro_position);
		// position.setText("22.58");
		// TextView wranp = (TextView) findViewById(R.id.tv_hydro_pwarn);
		// wranp.setText("32.5");
		// TextView flow = (TextView) findViewById(R.id.tv_hydro_fllow);
		// flow.setText("120m/s");
		// TextView direct = (TextView) findViewById(R.id.tv_hydro_direct);
		// direct.setText("1313");
//		TextView date = (TextView) findViewById(R.id.tv_hydro_date);
//		date.setText("12:30");
//		TextView wran = (TextView) findViewById(R.id.tv_hydro_warn);
//		wran.setText("35m");
//		TextView diff = (TextView) findViewById(R.id.tv_hydro_diff);
//		diff.setText("1m");
//		TextView guard = (TextView) findViewById(R.id.tv_hydro_guard);
//		guard.setText("28m");
//		TextView ensure = (TextView) findViewById(R.id.tv_hydro_ensure);
//		ensure.setText("10m");

		//initalStatisticCharts();
	}
	
	private double GetNum(String value){
		double result=0;
		try{
			result=Double.parseDouble(value);
		}catch(Exception e){e.printStackTrace();}
		return result;
	}
	
	private void initialInfo2(WaterStationSingle ws){
		try{
			TextView station = (TextView) findViewById(R.id.tv_hydro_stationname);
			station.setText(ws.stationName+"水位曲线图");
			TextView time=(TextView)findViewById(R.id.h_s_time);
			time.setText("["+ws.postTime+"报汛]");
			TextView warn=(TextView)findViewById(R.id.water_warning_position);
			warn.setText(ws.warning);
			TextView guard=(TextView)findViewById(R.id.water_fang_position);
			guard.setText(ws.guard);
			TextView dif=(TextView)findViewById(R.id.water_diff_position);
			dif.setText(ws.diff);
			TextView bao=(TextView)findViewById(R.id.water_bao_position);
			bao.setText(ws.ensure);
			
			if(ws!=null&&ws.positions!=null&&ws.positions.size()>0){
				
				String[] HorLabels=new String[ws.positions.size()];
				
				WaterStationSingle t=new WaterStationSingle();
				//这个pnull是需要的，方便最后一个点的文字显示
				//Postion pnull=t.new Postion();
				//pnull.time="null";
				//pnull.position=ws.positions.get(ws.positions.size()).position;
				//ws.positions.add(pnull);
				// draw random curve
				int num = ws.positions.size();
				double maxNum=0;
				double minNum=0;
				GraphViewData[] data = new GraphViewData[num];
				for (int i=0; i<num; i++) {
					String dt="";
					try {
						String pattern = "yyy-MM-dd HH:mm:ss"; //首先定义时间格式
				        SimpleDateFormat format = new SimpleDateFormat(pattern);//然后创建一个日期格式化类
				        String toConvertString = ws.positions.get(i).date;
				        Date convertResult = null;
				        convertResult = format.parse(toConvertString);
				        if(convertResult!=null){
				        	Calendar c=Calendar.getInstance();
							c.setTime(convertResult);
							dt=c.get(Calendar.DAY_OF_MONTH)+"日"+c.get(Calendar.HOUR_OF_DAY)+"时";
				        }
			        } catch (Exception e) {
			            e.printStackTrace();
			        }
					HorLabels[i]=dt;//ws.positions.get(i).date;
					//data[i] = new GraphViewData(i+1, i+1);
					data[i] = new GraphViewData(i+1, GetNum(ws.positions.get(i).position));
					try{
						double temp=Double.parseDouble(ws.positions.get(i).position);
						//double temp=i+1;
						if(temp>maxNum){
							maxNum=temp;
						}
						if(minNum>temp){
							minNum=temp;
						}
					}catch(Exception e){e.printStackTrace();}
				}
				GraphView graphView;
				// graph with dynamically genereated horizontal and vertical labels
					graphView = new LineGraphView(
							this
							, ""
					);
					((LineGraphView) graphView).setAutoHorLabels(HorLabels);
					((LineGraphView) graphView).setMyHorLabels(HorLabels);
					((LineGraphView) graphView).setBackgroundColor(0x4fffffff);
					((LineGraphView) graphView).setDrawBackground(true);
					((LineGraphView) graphView).setDrawText(true);
					((LineGraphView) graphView).setDrawTextDiff(10);
				// add data
				graphView.addSeries(new GraphViewSeries("水文图", new GraphViewSeriesStyle(0xffffffff, 3), data));
				// set view port, start=2, size=10
				graphView.getGraphViewStyle().setNumHorizontalLabels(6);
				graphView.setViewPort(num-5, 5);
				graphView.setScrollable(true);
				//graphView.setScalable(true);
				// set manual Y axis bounds
				maxNum=maxNum*1.5;
				graphView.setManualYAxisBounds(maxNum, minNum);
				LinearLayout hsv = (LinearLayout) findViewById(R.id.hsv_hydro_hs);
				hsv.addView(graphView);	
			}	
		}catch(Exception e){e.printStackTrace();}
	}
	
	private void initialInfo1(WaterStationSingle ws){
		try{
			try{
				LinearLayout hsv = (LinearLayout) findViewById(R.id.hsv_hydro_hs);
				if(ws!=null&&ws.positions!=null&&ws.positions.size()>0){
					
					String[] XLabel = new String[ws.positions.size()]; // X的刻度
					String[] YLabel = new String[ws.positions.size()]; // Y的刻度
					String[] Data=new String[ws.positions.size()];
					String[] Data1=new String[ws.positions.size()];
					double max=0;
					String maxStr=ws.positions.get(0).position;
					int maxInt=0;
					for(int i=0;i<ws.positions.size();i++){
						Data[i]=ws.positions.get(i).position;
						Data1[i]=ws.positions.get(i).time;
						XLabel[i]="h";
						
						try{
							double temp=Double.parseDouble(ws.positions.get(i).position);
							if(temp>max){
								max=temp;
								maxStr=ws.positions.get(i).position;
							}
						}catch(Exception e){e.printStackTrace();}
						try{
							String str = maxStr.substring(0, maxStr.indexOf("."));
							maxInt=Integer.parseInt(str)+1;
						}catch(Exception e){e.printStackTrace();}
					}
					
					WindowManager wm = this.getWindowManager();
					// 因为有7天所以八等份
					int width = wm.getDefaultDisplay().getWidth();
					int height=wm.getDefaultDisplay().getHeight();
					int perWidth = width / ws.positions.size();
					int perHeight=200/maxInt;//y轴定位200高,每一米占多少个像素点
					int XPoint = perWidth / 2; // 原点的X坐标
					int YPoint = 300;//y轴原点定在300处，//maxInt * 4+100; // 原点的Y坐标//显示-5到65度，小于0的全部放到-5处（65+5）*4放大四倍显示
					int XScale = perWidth; // X的刻度长度
					int perY=maxInt/ws.positions.size();//y轴每个显示点之间的平均米数
					int YScale = perY*perHeight; // Y的刻度长度，每个刻度见得像素距离
					int XLength = width; // X轴的长度
					int YLength = 200;//maxInt*perHeight + 20; // Y轴的长度
					
					//ylabel
					
					try{
						
						for(int i=0;i<ws.positions.size();i++){
							try{
								YLabel[i]=perY*i*perHeight+"";
							}catch(Exception e){e.printStackTrace();}
						}
					}catch(Exception e){e.printStackTrace();}
					
					HyLineChartView lcv1 = new HyLineChartView(this, XPoint, YPoint,
							XScale, YScale, XLength, YLength, XLabel, YLabel, Data,
							Data1, "图标的标题");
					hsv.addView(lcv1);	
				}				
			}catch(Exception e){e.printStackTrace();}
			
			TextView station = (TextView) findViewById(R.id.tv_hydro_stationname);
			station.setText(ws.stationName+"水位曲线图");
			TextView time=(TextView)findViewById(R.id.h_s_time);
			time.setText("["+ws.postTime+"报汛]");
			TextView warn=(TextView)findViewById(R.id.water_warning_position);
			warn.setText(ws.warning);
			TextView guard=(TextView)findViewById(R.id.water_fang_position);
			guard.setText(ws.guard);
			TextView dif=(TextView)findViewById(R.id.water_diff_position);
			dif.setText(ws.diff);
			TextView bao=(TextView)findViewById(R.id.water_bao_position);
			bao.setText(ws.ensure);
			
		}catch(Exception e){
			e.printStackTrace();
		}

	}

	private void initialInfo(WaterStationSingle ws){
		try{
			try{
				HydrologicalStationView hsv = (HydrologicalStationView) findViewById(R.id.hsv_hydro_hs);
				//hsv.setBackgroundResource(R.color.linearlayout_background);
				HashMap<Double, Double> map;
				//这里是显示的数值
				map = new HashMap<Double, Double>();
				if(ws!=null&&ws.positions!=null){
					for(int i=0;i<ws.positions.size();i++){
						map.put(Double.parseDouble(ws.positions.get(i).time), Double.parseDouble(ws.positions.get(i).position));
					}
					if(map.size()>0){
						hsv.SetTuView(map, 50, 10, "h", "m", false);

						hsv.setTotalvalue(50);
						hsv.setPjvalue(10);
						hsv.setMap(map);
						//hsv.setbg(0x7f060000);
						// hsv.setXstr("");
						// hsv.setYstr("");
						hsv.setMargint(20);
						hsv.setMarginb(50);
						hsv.setMstyle(Mstyle.Line);
					}
				}
				}catch(Exception e){e.printStackTrace();}
			
			TextView station = (TextView) findViewById(R.id.tv_hydro_stationname);
			station.setText(ws.stationName+"水位曲线图");
			TextView time=(TextView)findViewById(R.id.h_s_time);
			time.setText("["+ws.postTime+"报汛]");
			TextView warn=(TextView)findViewById(R.id.water_warning_position);
			warn.setText(ws.warning);
			TextView guard=(TextView)findViewById(R.id.water_fang_position);
			guard.setText(ws.guard);
			TextView dif=(TextView)findViewById(R.id.water_diff_position);
			dif.setText(ws.diff);
			TextView bao=(TextView)findViewById(R.id.water_bao_position);
			bao.setText(ws.ensure);
			
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	private void initalSpinner() {
		// river = (Spinner) findViewById(R.id.spin_hydro_river);
		// stations = (Spinner) findViewById(R.id.spin_hydro_station);

		List<HydroSpinnerItem> lst = new ArrayList<HydroSpinnerItem>();
		for (int i = 0; i < 10; i++) {
			/*
			 * 首先新建一个list,赋值 ID为序号
			 */
			HydroSpinnerItem item = new HydroSpinnerItem(i, "value of " + i);
			lst.add(item);
		}
		ArrayAdapter<HydroSpinnerItem> myaAdapter = new ArrayAdapter<HydroSpinnerItem>(
				this, android.R.layout.simple_spinner_item, lst);
		// river.setAdapter(myaAdapter);
		// river.setOnItemSelectedListener(new OnItemSelectedListener() {
		// public void onItemSelected(AdapterView<?> parent, View view,
		// int position, long id) {
		// /*
		// * ids是刚刚新建的list里面的ID
		// */
		// int ids = ((HydroSpinnerItem) river.getSelectedItem()).GetID();
		//
		// Toast.makeText(getApplicationContext(), String.valueOf(ids),
		// Toast.LENGTH_LONG).show();
		// }
		//
		// @Override
		// public void onNothingSelected(AdapterView<?> arg0) {
		// // TODO Auto-generated method stub
		//
		// }
		// });

		// stations.setAdapter(myaAdapter);
		// stations.setOnItemSelectedListener(new OnItemSelectedListener() {
		// public void onItemSelected(AdapterView<?> parent, View view,
		// int position, long id) {
		// /*
		// * ids是刚刚新建的list里面的ID
		// */
		// int ids = ((HydroSpinnerItem) stations.getSelectedItem())
		// .GetID();
		//
		// Toast.makeText(getApplicationContext(), String.valueOf(ids),
		// Toast.LENGTH_LONG).show();
		// }
		//
		// @Override
		// public void onNothingSelected(AdapterView<?> arg0) {
		// // TODO Auto-generated method stub
		//
		// }
		// });
	}

	private void initalStatisticCharts() {
		HydrologicalStationView hsv = (HydrologicalStationView) findViewById(R.id.hsv_hydro_hs);
		hsv.setBackgroundResource(R.color.linearlayout_background);
		HashMap<Double, Double> map;
		//这里是显示的数值
		map = new HashMap<Double, Double>();
		map.put(1.0, (double) 0);
		map.put(3.0, 25.0);
		map.put(4.0, 32.0);
		map.put(5.0, 41.0);
		map.put(6.0, 16.0);
		map.put(7.0, 36.0);
		map.put(8.0, 26.0);
		hsv.SetTuView(map, 50, 10, "x", "y", false);

		hsv.setTotalvalue(50);
		hsv.setPjvalue(10);
		hsv.setMap(map);
		// hsv.setXstr("");
		// hsv.setYstr("");
		hsv.setMargint(20);
		hsv.setMarginb(50);
		//hsv.setBackground(null);
		hsv.setMstyle(Mstyle.Line);

	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

}
